<template>
  <div class="user-navigation">
    <a-card title="目录" :bordered="false" style="width: 300px">
      <a-tree
        v-model:selectedKeys="selectedKeys"
        :expanded-keys="expandedKeys"
        :tree-data="treeData"
        @expand="handleExpand"
      >
        <template #title="{ title, key }">
          <span v-if="key === '0-0-1-0'" style="color: #1890ff">{{ title }}</span>
          <template v-else>{{ title }}</template>
        </template>
      </a-tree>
    </a-card>
  </div>
</template>
<script setup lang="ts">
import { inject, ref, watch } from "vue";
import type { TreeProps } from "ant-design-vue";
import difference from "lodash-es/difference";
import { Ref } from "vue";
import type  TreeNode  from "@/ts/TreeNode";



const expandedKeys = ref<string[]>([]);
const selectedKeys = ref<string[]>(["1-0"]);
const checkedKeys = ref<string[]>(["1-0"]);
// 动态数据
const  treeData  = ref<TreeProps["treeData"]>([]);

const articleContent = inject<Ref<string>>("content");
watch(
  () => articleContent.value,
  (newValue) => {
    // console.log(newValue);
    if (newValue) {
      const html = newValue;

// 核心正则表达式
const sectionRegex = /<(h[1-4])>([\s\S]*?)<\/\1>([\s\S]*?)(?=(?:<h[1-4]>)|$)/gi;

// 执行匹配
const matches: TreeNode[] = [];
let stack: TreeNode[] = []; // 维护层级关系栈
let match;
let indexCounter = 0;
while ((match = sectionRegex.exec(html)) !== null) {
 const level = parseInt(match[1].substring(1));
  const node: TreeNode = {
    title: match[2],
    key: `${level}-${indexCounter++}`, // 生成唯一key
    children: [],
  };
    // 调整栈深度到当前层级-1（h2对应层级2，父级在层级1）
  while (stack.length > level - 1) {
    stack.pop();
  }
   if (stack.length === 0) {
    // 根节点
    matches.push(node);
  } else {
    // 添加到父级的children
    stack[stack.length - 1].children.push(node);
  }

  stack.push(node); // 当前节点成为新的父级
}


treeData.value = matches;
    }
  },
);
// 处理树节点展开和收起事件
const handleExpand = (keys: string[], { expanded, node }) => {
  // node.parent add from 3.0.0-alpha.10
  const tempKeys = ((node.parent ? node.parent.children : treeData.value) || []).map(
    ({ key }) => key
  );
  if (expanded) {
    expandedKeys.value = difference(keys, tempKeys).concat(node.key);
  } else {
    expandedKeys.value = keys;
  }
};
</script>
<style>
.user-navigation {
  margin-top: 20px;
  padding: 20px;
  color: #ffffff;
}
</style>
